import 'package:dio/dio.dart';
import 'package:flutter_wgtool/OSNet/Core/OSNetAdapter.dart';
import 'package:flutter_wgtool/OSNet/Core/OSNetError.dart';
import 'package:flutter_wgtool/OSNet/Request/BaseRequest.dart';

/// Dio适配器
class OSNetDioAdapter extends OSNetAdapter {
  @override
  Future<OSNetResponse<T>> send<T>(BaseRequest request) async {
    var response, options = Options(headers: request.header);
    var error;
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        response = await Dio().get(request.url(), options: options);
      } else if (request.httpMethod() == HttpMethod.POST) {
        response = await Dio().post(request.url(), options: options);
      } else {
        response = await Dio().delete(request.url(), options: options);
      }
    } on DioError catch (e) {
      error = e;
      response = e.message;
    }

    if (error != null) {
      /// 抛出OSNetError
      throw OSNetError(response?.statusCode ?? -1, error.toString(),
          data: buildRes(response, request));
    }

    return buildRes(response, request);
  }

  /// 构建 OSNetResponse
  OSNetResponse<T> buildRes<T>(Response response, BaseRequest request) {
    return OSNetResponse(request,
        statusCode: response.statusCode,
        data: response.data,
        statusMessage: response.statusMessage,
        extra: response.extra);
  }
}
